<?php
//------------------------
// 公共函数
//-------------------------

use think\Response;

/*
 * 统一密码加密方式，如需变动直接修改此处
 * @param $password
 * @return string
 */
function password_hash_tp($password)
{
    return hash("md5", trim($password));
}

/*
 * 生成随机字符串
 * @param string $prefix
 * @return string
 */
function get_random($prefix = '')
{
    return $prefix . base_convert(time() * 1000, 10, 36) . "_" . base_convert(microtime(), 10, 36) . uniqid();
}

/*
 * 对查询结果集进行排序
 * @access public
 * @param array $list   查询结果
 * @param string $field 排序的字段名
 * @param array $sortBy 排序类型
 *                      asc正向排序 desc逆向排序 nat自然排序
 * @return array|bool
 */
function list_sort_by($list, $field, $sortBy = 'asc')
{
    if (is_array($list)) {
        $refer = $resultSet = [];
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortBy) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc': // 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
            $resultSet[] = &$list[$key];

        return $resultSet;
    }

    return false;
}

/*
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;

    return round($size, 2) . $delimiter . $units[$i];
}

/*
 * 生成一定长度的UUID
 *
 * @param int $length
 *
 * @return string
 */
function get_uuid($length = 16)
{
    mt_srand((double)microtime()*10000);
    $uuid = sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
    $str = base64_encode($uuid);
    return substr($str,  mt_rand(0, strlen($str) - $length), $length);
}

/*
 * 框架内部默认ajax返回
 * @param string $msg      提示信息
 * @param string $data     附加数据
 * @param int $code        错误码
 */
function ajax_return_adv($msg = '操作成功', $code = 0, $data=[]){
    return ajax_return($data, $msg, $code);
}
/*
 * 返回错误json信息
 */
function ajax_return_adv_error($msg = '', $code = 0){
    return ajax_return_adv($msg,$code);
}
/*
 * ajax数据返回，规范格式
 * @param array $data   返回的数据，默认空数组
 * @param string $msg   信息
 * @param int $code     错误码
 */
function ajax_return($data = [], $msg = "", $code = 0){
    $ret = ["code" => $code, "msg" => $msg, "data" => $data];
    return Response::create($ret, 'json');
}

/*
 * 返回标准错误json信息
 * @param array $data   返回的数据，默认空数组
 * @param string $msg   信息
 * @param int $code     错误码
 */
function ajax_return_error($msg = "出现错误", $code = 0, $data = []){
    return ajax_return($data, $msg, $code);
}

/*
 * 生成唯一订单号
 * */
function build_order_no($fix){
    return $fix.date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 3);
}
//图片保存
function getSaveImgDir($d='images'){
    return (isset($GLOBALS['SysDataBaseConfig']) ? "/test/$d/":"/tmp/$d/");
}
//Base64图片
function uploadBase64Images($base64_image_content){
    $dir = getSaveImgDir();
    $return_dir = $dir.date('Ymd',time())."/";
    $new_dir = ROOT_PATH.'public'.$return_dir;
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        if (!is_dir($new_dir)){ mkdir($new_dir); }
        $file_name = md5(time().rand(0,100)).".$type";
        $new_file = $new_dir.$file_name;
        if ( file_put_contents($new_file, base64_decode(str_replace($result[1],'',$base64_image_content)))){
            return $return_dir.$file_name;
        }
    }
    return "";
}
//资源图片保存
function DownLoadQr($url){
    if( $url == "" ){
        return false;
    }
    $dir = getSaveImgDir();
    $return_dir = $dir.date('Ymd',time())."/";
    $new_dir = ROOT_PATH.'public'.$return_dir;
    if ( !is_dir($new_dir) ){ mkdir($new_dir); }
    $file_name = md5(time().rand(0,100)).".jpg";
    $new_file = $new_dir.$file_name;
    if( file_put_contents($new_file,$url) ) {
        return $return_dir.$file_name;
    }
    return "";
}
function downExternalUrlImg($url){
    set_time_limit ( 0 );
    $url = trim ( $url );
    $curl = curl_init ();
    // 设置你需要抓取的URL
    curl_setopt ( $curl, CURLOPT_URL, $url );
    // 设置header
    curl_setopt ( $curl, CURLOPT_HEADER, 0 );
    // 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
    curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
    // 运行cURL，请求网页
    $file = curl_exec ( $curl );
    // 关闭URL请求
    curl_close ( $curl );
    // 将文件写入获得的数据
    $dir = getSaveImgDir('head');
    //if ( !is_dir(ROOT_PATH.'public'.$dir) ){ mkdir(ROOT_PATH.'public'.$dir); }
    $return_dir = $dir.date('Ymd',time())."/";
    $new_dir = ROOT_PATH.'public'.$return_dir;
    //if ( !is_dir(ROOT_PATH.'public'.$dir) ){ mkdir(ROOT_PATH.'public'.$dir); }
    if ( !is_dir($new_dir) ){ mkdir($new_dir); }
    $file_name = md5(time().rand(0,100)).".jpg";
    $new_file = $new_dir.$file_name;
    $write = @fopen ( $new_file, "w" );
    if ($write == false) {
        return false;
    }
    if (fwrite ( $write, $file ) == false) {
        return false;
    }
    if (fclose ( $write ) == false) {
        return false;
    }
    return $return_dir.$file_name;
}
/*图标文字转换 最好是升级数据库 */
function iconReplaceText($text=''){
    return preg_replace_callback('/[\xf0-\xf7].{3}/', function($r) { return '@E' . base64_encode($r[0]);}, $text);
}
function textReplaceIcon($text=''){
    return preg_replace_callback('/@E(.{6}==)/', function($r) {return base64_decode($r[1]);}, $text);
}

function getDoMain(){
    return 'https://'.$_SERVER['HTTP_HOST'];
}

/**
 * 秒转时间
 * @access  public
 * @param (int)$start_time 开始时间
 * @param (int)$end_time 结束时间
 * @return  string
 */
function secondToDiffTime($start_time,$end_time){
    $second = $end_time - $start_time;
    if( $second > 864000*3 ) {
        return date('Y-m-d H:i',$start_time);
    }
    $hh = 0; //时
    $ii = floor($second/60); //分
    $ss = $second%60; //秒
    $dd = 0;
    if( 60 < $ii ) {
        $hh = floor($ii/60);
        $ii = $ii%60;
    }
    if( 24 < $hh ) {
        $dd	= floor($hh/24);
        $hh = $hh%60;
    }
    if( 0 < $dd ) {
        return date('Y-m-d',$start_time);
    }
    if( 0 < $hh ) {
        return $hh.'小时前';
    }
    if( 0 < $ii ) {
        return $ii.'分钟前';
    }
    return $ss.'秒前';
}
function num2cnHour($h=0){
    switch ( (int)$h ){
        case $h<7:
            $t = '凌晨';
            break;
        case $h<13:
            $t = '上午';
            break;
        case $h<19:
            $t = '下午';
            break;
        default:
            $t = '晚上';
    }
    return " {$t}{$h}点";
}

//获得视频文件的缩略图 $file视频，$time时间，图片名称为视频地址
function getVideoCover($file,$time=1) {
    $strlen = strlen($file);
    $videoCover = substr($file,0,$strlen-4);
    $videoCoverName = $videoCover.'.jpg';//缩略图命名
    //exec("/usr/local/bin/ffmpeg -i ".$file." -y -f mjpeg -ss ".$time." -t 0.001 -s 320x154 ".$videoCoverName,$out,$status);
    exec("/usr/local/bin/ffmpeg -i ".$file." -y -f mjpeg -ss ".$time." -t 0.001 ".$videoCoverName,$out,$status);
    return $status;
}
//计算内容
function countContentNum($box){
    $forCharge = [];
    foreach($box as $k1=>$v1) {
        !isset($forCharge[$v1['type']]) && $forCharge[$v1['type']] = 0;
        switch ($v1['type']) {
            case 'txt':
                $forCharge[$v1['type']] += mb_strlen($v1['val'],'utf-8');
                break;
            default:
                $forCharge[$v1['type']] += 1;
                break;
        }
    }
    $txt = 0;$img = '';$audio = '';$video ='';
    foreach ( $forCharge as $k1=>$v1){
        switch ( $k1 ) {
            case 'txt':
                $txt = '，'.$v1.'字';
                break;
            case 'img':
                $img = '，'.$v1.'个图';
                break;
            case 'audio':
                $audio = '，'.$v1.'个录音';
                break;
            case 'video':
                $video = '，'.$v1.'个视频';
                break;
        }
    }
    return'全文共'.mb_substr($txt.$img.$audio.$video,1);
}


/**
 * 节点遍历
 *
 * @param        $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int    $root
 *
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = [];
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            if ($data instanceof \think\Model) {
                $list[$key] = $data->toArray();
            }
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            if (!isset($list[$key][$child])) {
                $list[$key][$child] = [];
            }
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }

    return $tree;
}

/**
 * 多维数组合并（支持多数组）
 * @return array
 */
function array_merge_multi()
{
    $args = func_get_args();
    $array = [];
    foreach ($args as $arg) {
        if (is_array($arg)) {
            foreach ($arg as $k => $v) {
                if (is_array($v)) {
                    $array[$k] = isset($array[$k]) ? $array[$k] : [];
                    $array[$k] = array_merge_multi($array[$k], $v);
                } else {
                    $array[$k] = $v;
                }
            }
        }
    }

    return $array;
}